import dayjs from "dayjs";
import editForm from "../Table.vue";
import recordForm from "../record.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import type { FormItemProps } from "../utils/types";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection } from "@pureadmin/utils";
import {
  getTaskList,
  addTask,
  deleteTask,
  runTask,
  pauseTask,
  resumeTask,
  getTaskLogs
} from "@/api/system";
import { reactive, ref, onMounted, h } from "vue";

import { getFilter } from "@/utils/filter";

export function useRole() {
  const form = reactive({
    name: "",
    type: ""
  });
  const curRow = ref();
  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const isLinkage = ref(false);
  const switchLoadMap = ref({});
  const { switchStyle } = usePublicHooks();
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "任务ID",
      prop: "id",
      hide: true
    },
    {
      label: "任务名字",
      prop: "name"
    },
    {
      label: "ssh脚本内容",
      prop: "content"
    },
    {
      label: "http地址",
      prop: "url"
    },
    {
      label: "状态",
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.status}
          active-value={1}
          inactive-value={0}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      ),
      minWidth: 90
    },
    {
      label: "执行周期",
      cellRenderer: scope => (
        <el-tag size="mini" type="info">
          {scope.row.triggerType} - {scope.row.type}
        </el-tag>
      )
    },
    {
      label: "上次执行时间",
      prop: "lastRunTime",
      minWidth: 160,
      formatter: ({ lastRunTime }) =>
        dayjs(lastRunTime * 1000).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "创建时间",
      prop: "createtime",
      minWidth: 160,
      formatter: ({ createtime }) =>
        dayjs(createtime * 1000).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];

  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.status === 0 ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.name
      }</strong>任务吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        if (row.status == 1) {
          // 启动任务
          handleResume(row, index);
        } else {
          // 暂停任务
          handlePause(row, index);
        }
      })
      .catch(() => {
        row.status === 0 ? (row.status = 1) : (row.status = 0);
      });
  }

  function handleDelete(row) {
    deleteTask({ task_id: row.id }).then(res => {
      if (res.code) {
        // onSearch();
        message(`您删除了任务名称为${row.name}的这条数据`, { type: "success" });
      } else {
        message("删除失败", { type: "error" });
      }
    });
  }

  function handleRun(row) {
    runTask({ task_id: row.id }).then(res => {
      if (res.code) {
        message(`您执行了任务名称为${row.name}的这条数据`, { type: "success" });
      } else {
        message("执行失败", { type: "error" });
      }
    });
  }

  function handleLogs(row) {
    // id 参数传递
    addDialog({
      title: "查看日志",
      width: "70%",
      props: {
        id: row.id
      },
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(recordForm),
      beforeSure: (done, { options }) => {
        console.log("options", options);
        done();
        // recordForm
        getTaskLogs({ id: row.id }).then(res => {
          if (res.data?.list) {
            console.log(res.data);
          } else {
            message("获取日志失败", { type: "error" });
          }
        });
      }
    });
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = parseInt(val as any);
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  async function onSearch() {
    loading.value = true;
    let filter = await getFilter(form);
    //特殊处理
    filter = filter.map(item => {
      if (item.field === "type") {
        item.operator = "=";
        item.value = item.value.replace(/%/g, "");
      }
      return item;
    });

    let ListRequest = {
      page: pagination.currentPage,
      limit: pagination.pageSize,
      filter,
      order: "desc"
    };

    const { data } = await getTaskList(ListRequest);
    dataList.value = data.list;
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.currentPage;

    loading.value = false;
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}计划任务`,
      props: {
        formInline: {
          name: row?.name ?? "",
          type: row?.type ?? "shhscript",
          triggerType: row?.triggerType ?? "interval",
          month: row?.month ?? 0,
          day: row?.day ?? 0,
          hour: row?.hour ?? 0,
          minute: row?.minute ?? 0,
          second: row?.second ?? 1,
          role: row?.role ?? "",
          content: row?.content ?? "",
          url: row?.url ?? "",
          url_agent: row?.url_agent ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了计划任务名称为${curData.name}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          console.log("valid", valid);
          if (valid) {
            // 表单规则校验通过
            if (title === "新增") {
              console.log("curData", curData);
              addTask(curData).then(res => {
                if (res.code) {
                  chores();
                } else {
                  message(res.msg, { type: "error" });
                }
              });
            }
          }
        });
      }
    });
  }

  /** 高亮当前权限选中行 */
  function rowStyle({ row: { id } }) {
    return {
      cursor: "pointer",
      background: id === curRow.value?.id ? "var(--el-fill-color-light)" : ""
    };
  }

  onMounted(async () => {
    onSearch();
  });

  function handlePause(row, index) {
    pauseTask({ task_id: row.id }).then(res => {
      if (res.code) {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: false
          }
        );
        message(`您暂停了任务名称为${row.name}的这条数据`, { type: "success" });
      } else {
        message("暂停失败", { type: "error" });
      }
    });
  }

  function handleResume(row, index) {
    resumeTask({ task_id: row.id }).then(res => {
      if (res.code) {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: false
          }
        );
        message(`您恢复了任务名称为${row.name}的这条数据`, { type: "success" });
      } else {
        message("恢复失败", { type: "error" });
      }
    });
  }

  return {
    form,
    isShow,
    curRow,
    loading,
    columns,
    rowStyle,
    dataList,
    isLinkage,
    pagination,
    // buttonClass,
    onSearch,
    resetForm,
    openDialog,
    handleDelete,
    handleRun,
    handleLogs,
    // handleDatabase,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
